package com.bjpowernode.other.readwritelock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写都存在
 */
public class ReadWriteLock02 {
    public static void main(String[] args) {
        ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

        //写
        Runnable writeTask = () -> {
            try {
                //获取写锁
                readWriteLock.writeLock().lock();
                TimeUnit.SECONDS.sleep(3);
                //模拟写入
                System.out.println(Thread.currentThread().getName() + ":" + System.currentTimeMillis());
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }finally {
                //释放锁
                readWriteLock.writeLock().unlock();
            }
        };

        //模拟读操作
        Runnable readTask = () -> {
            try {
                //获取读锁
                readWriteLock.readLock().lock();
                TimeUnit.SECONDS.sleep(3);
                //模拟读取
                System.out.println(Thread.currentThread().getName() + ":" + System.currentTimeMillis());
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }finally {
                //释放锁
                readWriteLock.readLock().unlock();
            }
        };

        new Thread(writeTask).start();
        new Thread(readTask).start();
    }
}
